package business.database.sqliteMaescorp

import domain.Center
import groovy.sql.Sql
import java.util.HashMap;
import java.util.List;

/**
 * DAO para la tabla Corp
 * @author Administrador
 *
 */
public class CentersCorpsDAO {
	
	private def Sql sqlite;
	
	/**
	 * Inicializamos la clase con la instance de SQL
	 * @param sql
	 */
	public CentersCorpsDAO(Sql sql) {
		sqlite = sql;
	}
	
	/**
	 * Crea la tabla
	 */
	public void create() {
		sqlite.execute "CREATE TABLE  IF NOT EXISTS Centers_Corps (idCe integer NOT NULL, idCorp integer NOT NULL, UNIQUE (idCe, idCorp) "+
		 	", FOREIGN KEY(idCorp) REFERENCES Corp(idCorp) "+
			 ", FOREIGN KEY(idCe) REFERENCES Center(idCe));"
	  
	   sqlite.execute "create index IF NOT EXISTS idx_idCe on centers_corps(idCe);"
	   sqlite.execute "create index IF NOT EXISTS idx_idSoloCorp on centers_corps(idCorp);"
	}
	
		
	/**
	 * Inserta un centerscorps
	 * @param idce
	 * 
	 * @param idcorp
	 */
	public void insert(int idce, int idcorp) {
		sqlite.execute "INSERT INTO Centers_Corps values (${idce}, ${idcorp})";
	}
	
	/**
	 * Actualiza el centro del corp
	 * @param idce
	 * @param idcorp
	 */
	public void updateIdCe(int idce, int idcorp) {
		sqlite.execute "Update Centers_Corps set idce = ${idce} where idcorp = ${idcorp}";
	}
	
	/**
	* Borra el corp
	* @param idcorp
	*/
   public void delete(int idcorp) {
	  sqlite.execute("delete from centers_corps where idcorp = ${idcorp}");
   }
   
   /**
    * comprueba si ya existe la relacion entre idce e idcorp
    * @param idce
    * @param idcorp
    * @return
    */
   public boolean exists(int idce, int idcorp) {
	   def cen = sqlite.firstRow("Select idCe from Centers_Corps WHERE idCe =${idce} and idcorp = ${idcorp}")
	   
	   return ((cen == null)&&(cen[0] != null));
		   
   }

	
}
